package com.xy.biz.base.support.bizcode;

import com.xy.biz.base.domain.bo.BizCodeBO;
import com.xy.lang.util.CalendarUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

import static com.xy.biz.base.support.bizcode.BizCodeGenerator.ALGORITHM_SERVICE_PREFIX;
import static com.xy.biz.base.support.bizcode.BizCodeGenerator.ALGORITHM_SIMPLE;

@Slf4j
@Service(ALGORITHM_SERVICE_PREFIX + ALGORITHM_SIMPLE)
public class SimpleBizCodeGenerator implements BizCodeGenerator {

    private final static long timestampOffset = 18500; // 2020-08-26

    @Override
    public long getTimestamp() {
        return (CalendarUtils.toEpochSecond() / 86400) - timestampOffset;
    }

    @Override
    public String generate(BizCodeBO bizCodeBO, int nextValue) {
        String dateFormat = bizCodeBO.getDateFormat();
        if(!StringUtils.hasText(dateFormat)) {
            dateFormat = "yyyyMMdd";
        }
        String datePart = "";
        try {
            datePart = CalendarUtils.format(LocalDateTime.now(), dateFormat);
        } catch (Exception e) {
            log.error("错误的时间格式：" + dateFormat, e);
        }
        long tenantId = (null == bizCodeBO.getTenantId()) ? 0 : bizCodeBO.getTenantId();
        int numberLength = bizCodeBO.getNumberLength() == null || bizCodeBO.getNumberLength() < 1 ? 1 : bizCodeBO.getNumberLength();
        if(tenantId < 1L) {
            return datePart
                    + String.format("%0" + numberLength + "d", nextValue);
        } else {
            return datePart
                    + String.format("%03d", tenantId)
                    + String.format("%0" + numberLength + "d", nextValue);
        }
    }

    public static void main(String[] args) {
        System.out.println(CalendarUtils.format(LocalDateTime.now(), "YYMMdd") + String.format("%04d", 1));
        System.out.println(CalendarUtils.format(LocalDateTime.now(), "YYMMdd") + String.format("%04d", 2));
        System.out.println(CalendarUtils.format(LocalDateTime.now(), "YYMMdd") + String.format("%04d", 9999));
        System.out.println(CalendarUtils.format(LocalDateTime.now(), "YYMMdd") + String.format("%04d", 10000));
    }

}
